package com.bangcommunity.bbframe.dynconfig.id;

import com.bangcommunity.bbframe.common.utils.id.DangDangIdFactory;
import com.bangcommunity.bbframe.common.utils.id.DangDangIdGenerator;
import com.bangcommunity.bbframe.common.utils.lang.StringUtils;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 *
 * @author tanghc
 * @date 17/1/23
 */
public class DistDangDangId {
    static final Logger logger = LoggerFactory.getLogger(DistDangDangId.class);
    private static ConcurrentMap<String, DistributedAtomicLong> seeds = new ConcurrentHashMap<>();

    private DistDangDangId() {
    }

    private static class DistDangDangIdHolder {
        private static DistDangDangId instance = new DistDangDangId();
        private static final String dist_dang_id_key = "d_d_i_k";
    }

    public static DistDangDangId getInstance() {
        return DistDangDangIdHolder.instance;
    }

    public long id(final String key) {
        logger.debug("start get id: key={}", key);
        String wrapKey = wrapKey(key);
        DangDangIdGenerator idGenerator = DangDangIdFactory.getInstance().getIdGenerator(wrapKey);
        idGenerator.setWorkerId((long) DistAppIdentifier.getInstance().appIndentifier());
        return idGenerator.generateId();
    }

    public String humanRead(final String key, final long id) {
        String wrapKey = wrapKey(key);
        DangDangIdGenerator idGenerator = DangDangIdFactory.getInstance().getIdGenerator(wrapKey);
        idGenerator.setWorkerId((long) DistAppIdentifier.getInstance().appIndentifier());
        return idGenerator.idForHuman(id);
    }

    private String wrapKey(final String rawKey) {
        return DistDangDangIdHolder.dist_dang_id_key + StringUtils.trimToEmpty(rawKey);
    }
}
